package system

import (
	"counter-help/admin/server/global"
	"counter-help/admin/server/model/common/request"
	"counter-help/admin/server/model/common/response"
	"counter-help/admin/server/model/system"
	"counter-help/admin/server/service"
	"fmt"
	"time"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type UUIDLicenseApi struct{}

// ValidateUUID 验证UUID
func (u *UUIDLicenseApi) ValidateUUID(c *gin.Context) {

	uuid := c.Query("uuid")
	if uuid == "" {
		global.GVA_LOG.Error("参数错误: UUID为空")
		response.FailWithCodeMessage(7, "UUID不能为空", c)
		return
	}

	// 验证UUID长度
	if len(uuid) != 36 {
		global.GVA_LOG.Error("UUID长度不正确", zap.String("uuid", uuid))
		response.FailWithCodeMessage(7, "UUID长度必须为36位", c)
		return
	}

	global.GVA_LOG.Info("接收到验证UUID请求", zap.String("uuid", uuid))

	code, remainingDays, err := service.ServiceGroupApp.SystemServiceGroup.UUIDLicenseService.ValidateUUID(uuid)
	if err != nil {
		global.GVA_LOG.Error("验证失败!", zap.Error(err))
		response.FailWithCodeMessage(code, err.Error(), c)
		return
	}

	// 返回验证成功信息以及剩余天数
	// 格式化剩余时间字符串
	// expiryMessage := ""
	// if remainingDays >= 30 {
	// 	months := remainingDays / 30
	// 	days := remainingDays % 30
	// 	expiryMessage = fmt.Sprintf("还有%d月%d天过期", months, days)
	// } else {
	// 	expiryMessage = fmt.Sprintf("还有%d天过期", remainingDays)
	// }
	c.JSON(200, gin.H{
		"code":    0,
		"message": "验证成功",
		"data":    remainingDays,
	})
}

// CreateUUIDLicense 创建UUID许可证
func (u *UUIDLicenseApi) CreateUUIDLicense(c *gin.Context) {
	var tempLicense struct {
		UUID             string `json:"uuid"`
		ExpireTime       int64  `json:"expireTime"` // 使用毫秒级时间戳
		IsActive         bool   `json:"isActive"`
		Description      string `json:"description"`
		DailyAccessLimit int    `json:"dailyAccessLimit"`
		TotalAccessLimit int    `json:"totalAccessLimit"`
	}

	err := c.ShouldBindJSON(&tempLicense)
	if err != nil {
		global.GVA_LOG.Error("参数解析失败!", zap.Error(err))
		response.FailWithMessage("参数错误: "+err.Error(), c)
		return
	}

	// 将毫秒级时间戳转换为 time.Time
	expireTime := time.UnixMilli(tempLicense.ExpireTime)

	// 验证过期时间不能早于当前时间
	if expireTime.Before(time.Now()) {
		global.GVA_LOG.Error("过期时间不能早于当前时间")
		response.FailWithMessage("过期时间不能早于当前时间", c)
		return
	}

	license := system.UUIDLicense{
		UUID:             tempLicense.UUID,
		ExpireTime:       expireTime,
		IsActive:         tempLicense.IsActive,
		Description:      tempLicense.Description,
		DailyAccessLimit: tempLicense.DailyAccessLimit,
		TotalAccessLimit: tempLicense.TotalAccessLimit,
		CurrentDayAccess: 0,
		TotalAccess:      0,
		LastAccessDate:   time.Now(),
	}

	// 参数验证
	if license.UUID == "" {
		response.FailWithMessage("UUID不能为空", c)
		return
	}

	// 设置默认值
	if license.DailyAccessLimit == 0 {
		license.DailyAccessLimit = 100
	}
	if license.TotalAccessLimit == 0 {
		license.TotalAccessLimit = 10000
	}
	license.IsActive = true // 默认激活

	global.GVA_LOG.Info("接收到创建UUID请求",
		zap.String("uuid", license.UUID),
		zap.Time("expireTime", license.ExpireTime),
		zap.Int("dailyAccessLimit", license.DailyAccessLimit),
		zap.Int("totalAccessLimit", license.TotalAccessLimit),
		zap.String("description", license.Description))

	err = service.ServiceGroupApp.SystemServiceGroup.UUIDLicenseService.CreateUUIDLicense(&license)
	if err != nil {
		global.GVA_LOG.Error("创建失败!", zap.Error(err))
		// 检查是否是唯一性约束错误
		if err.Error()[4:8] == "1062" { // MySQL错误码1062表示重复键
			response.FailWithMessage("创建失败: UUID已存在，请使用其他UUID", c)
			return
		}
		response.FailWithMessage("创建失败: "+err.Error(), c)
		return
	}

	response.OkWithMessage("创建成功", c)
}

// UpdateUUIDLicense 更新UUID许可证
func (u *UUIDLicenseApi) UpdateUUIDLicense(c *gin.Context) {
	var tempLicense struct {
		UUID             string `json:"uuid"`
		ExpireTime       int64  `json:"expireTime"` // 使用毫秒级时间戳
		IsActive         bool   `json:"isActive"`
		Description      string `json:"description"`
		DailyAccessLimit int    `json:"dailyAccessLimit"`
		TotalAccessLimit int    `json:"totalAccessLimit"`
	}

	err := c.ShouldBindJSON(&tempLicense)
	if err != nil {
		global.GVA_LOG.Error("参数解析失败!", zap.Error(err))
		response.FailWithMessage("参数错误: "+err.Error(), c)
		return
	}

	license := system.UUIDLicense{
		UUID:             tempLicense.UUID,
		ExpireTime:       time.UnixMilli(tempLicense.ExpireTime),
		IsActive:         tempLicense.IsActive,
		Description:      tempLicense.Description,
		DailyAccessLimit: tempLicense.DailyAccessLimit,
		TotalAccessLimit: tempLicense.TotalAccessLimit,
	}

	global.GVA_LOG.Info("接收到更新UUID请求",
		zap.String("uuid", license.UUID),
		zap.Time("expireTime", license.ExpireTime),
		zap.Int("dailyAccessLimit", license.DailyAccessLimit),
		zap.Int("totalAccessLimit", license.TotalAccessLimit),
		zap.String("description", license.Description))

	err = service.ServiceGroupApp.SystemServiceGroup.UUIDLicenseService.UpdateUUIDLicense(&license)
	if err != nil {
		global.GVA_LOG.Error("更新失败!", zap.Error(err))
		response.FailWithMessage("更新失败: "+err.Error(), c)
		return
	}

	response.OkWithMessage("更新成功", c)
}

// DeleteUUIDLicense 删除UUID许可证
func (u *UUIDLicenseApi) DeleteUUIDLicense(c *gin.Context) {
	uuid := c.Query("uuid")
	if uuid == "" {
		global.GVA_LOG.Error("参数错误: UUID为空")
		response.FailWithMessage("UUID不能为空", c)
		return
	}
	global.GVA_LOG.Info("接收到删除UUID请求", zap.String("uuid", uuid))

	err := service.ServiceGroupApp.SystemServiceGroup.UUIDLicenseService.DeleteUUIDLicense(uuid)
	if err != nil {
		global.GVA_LOG.Error("删除失败!", zap.Error(err))
		response.FailWithMessage("删除失败: "+err.Error(), c)
		return
	}

	response.OkWithMessage("删除成功", c)
}

// GetUUIDList 获取UUID许可证列表
func (u *UUIDLicenseApi) GetUUIDList(c *gin.Context) {
	var pageInfo request.PageInfo
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		global.GVA_LOG.Error("获取参数失败!", zap.Error(err))
		response.FailWithMessage("获取参数失败", c)
		return
	}
	global.GVA_LOG.Info("接收到获取UUID列表请求", zap.Any("pageInfo", pageInfo))

	list, total, err := service.ServiceGroupApp.SystemServiceGroup.UUIDLicenseService.GetUUIDList(pageInfo)
	if err != nil {
		global.GVA_LOG.Error("获取列表失败!", zap.Error(err))
		response.FailWithMessage("获取列表失败: "+err.Error(), c)
		return
	}

	response.OkWithDetailed(response.PageResult{
		List:     list,
		Total:    total,
		Page:     pageInfo.Page,
		PageSize: pageInfo.PageSize,
	}, "获取成功", c)
}

// ResetDailyAccess 手动重置所有UUID的当日访问次数
func (u *UUIDLicenseApi) ResetDailyAccess(c *gin.Context) {
	global.GVA_LOG.Info("接收到手动重置当日访问次数请求")
	err := service.ServiceGroupApp.SystemServiceGroup.UUIDLicenseService.ResetDailyAccess()
	if err != nil {
		global.GVA_LOG.Error("重置当日访问次数失败!", zap.Error(err))
		response.FailWithMessage("重置失败: "+err.Error(), c)
		return
	}

	response.OkWithMessage("重置成功", c)
}

// RenewUUID 续费UUID许可证
func (u *UUIDLicenseApi) RenewUUID(c *gin.Context) {
	global.GVA_LOG.Info("-----------------------------")
	var renewInfo struct {
		UUID       string `json:"uuid"`
		RenewType  string `json:"renewType"` // 'day' 或 'month'
		RenewValue int    `json:"renewValue"`
	}

	err := c.ShouldBindJSON(&renewInfo)
	if err != nil {
		global.GVA_LOG.Error("参数解析失败!", zap.Error(err))
		response.FailWithMessage("参数错误: "+err.Error(), c)
		return
	}

	fmt.Println("解析后的参数:", renewInfo)

	// 参数校验
	if renewInfo.UUID == "" {
		global.GVA_LOG.Error("参数校验失败: UUID为空")
		response.FailWithMessage("UUID不能为空", c)
		return
	}

	if renewInfo.RenewType != "day" && renewInfo.RenewType != "month" {
		global.GVA_LOG.Error("参数校验失败: 续费类型无效", zap.String("renewType", renewInfo.RenewType))
		response.FailWithMessage("续费类型必须是'day'或'month'", c)
		return
	}

	if renewInfo.RenewValue <= 0 {
		global.GVA_LOG.Error("参数校验失败: 续费时长无效", zap.Int("renewValue", renewInfo.RenewValue))
		response.FailWithMessage("续费时长必须大于0", c)
		return
	}

	global.GVA_LOG.Info("接收到续费UUID请求",
		zap.String("uuid", renewInfo.UUID),
		zap.String("renewType", renewInfo.RenewType),
		zap.Int("renewValue", renewInfo.RenewValue))

	err = service.ServiceGroupApp.SystemServiceGroup.UUIDLicenseService.RenewUUID(renewInfo.UUID, renewInfo.RenewType, renewInfo.RenewValue)
	if err != nil {
		global.GVA_LOG.Error("续费失败!", zap.Error(err))
		response.FailWithMessage("续费失败: "+err.Error(), c)
		return
	}

	response.OkWithMessage("续费成功", c)
}

// GetUUIDRenewalRecords 获取UUID续费记录
func (u *UUIDLicenseApi) GetUUIDRenewalRecords(c *gin.Context) {
	uuid := c.Query("uuid")
	if uuid == "" {
		global.GVA_LOG.Error("参数错误: UUID为空")
		response.FailWithMessage("UUID不能为空", c)
		return
	}

	global.GVA_LOG.Info("接收到获取UUID续费记录请求", zap.String("uuid", uuid))

	records, err := service.ServiceGroupApp.SystemServiceGroup.UUIDLicenseService.GetUUIDRenewalRecords(uuid)
	if err != nil {
		global.GVA_LOG.Error("获取续费记录失败!", zap.Error(err))
		response.FailWithMessage("获取续费记录失败: "+err.Error(), c)
		return
	}

	response.OkWithDetailed(records, "获取成功", c)
}

// GetUUIDExportData 获取UUID导出数据（包含续费信息）
func (u *UUIDLicenseApi) GetUUIDExportData(c *gin.Context) {
	var pageInfo request.PageInfo
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	global.GVA_LOG.Info("接收到获取UUID导出数据请求", zap.Any("pageInfo", pageInfo))

	list, total, err := service.ServiceGroupApp.SystemServiceGroup.UUIDLicenseService.GetUUIDExportData(pageInfo)
	if err != nil {
		global.GVA_LOG.Error("获取UUID导出数据失败!", zap.Error(err))
		response.FailWithMessage("获取UUID导出数据失败: "+err.Error(), c)
		return
	}

	response.OkWithDetailed(response.PageResult{
		List:     list,
		Total:    total,
		Page:     pageInfo.Page,
		PageSize: pageInfo.PageSize,
	}, "获取成功", c)
}
